package com.datastructure.test.diameterofbinarytree;

public class DiameterOfBinaryTree {

    public int max = Integer.MIN_VALUE;
    public static void main(String[] args) {

    }

    public int diameterOfBinaryTree (TreeNode root) {
        // write code here
        if(root==null){
            return 0;
        }
        computeMaxDiameter(root);
        return max;
    }

    private void computeMaxDiameter(TreeNode root) {
        if(root==null){
            return;
        }
        max=Math.max(max,getMaxDepthOfBinaryTree(root.left)+getMaxDepthOfBinaryTree(root.right));
        computeMaxDiameter(root.left);
        computeMaxDiameter(root.right);
    }

    public int getMaxDepthOfBinaryTree(TreeNode root){
        if(root==null){
            return 0;
        }
        int max = 0;
        if(root.left!=null){
            max=Math.max(max,getMaxDepthOfBinaryTree(root.left));
        }
        if(root.right!=null){
            max=Math.max(max,getMaxDepthOfBinaryTree(root.right));
        }
        return max+1;
    }
}

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}
